import java.io.IOException;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpServerChannel;

public class SCTPServer {
	static int SERVER_PORT = 3456;

	public static void main(String[] args) throws IOException {
		SctpServerChannel ssc = SctpServerChannel.open();
		InetSocketAddress serverAddr = new InetSocketAddress(SERVER_PORT);
		ssc.bind(serverAddr);

		ByteBuffer buf = ByteBuffer.allocateDirect(60);
		CharBuffer cbuf = CharBuffer.allocate(60);
		Charset charset = Charset.forName("ISO-8859-1");
		CharsetEncoder encoder = charset.newEncoder();
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
		String in;
		while (true) {
			SctpChannel sc;

			if((sc = ssc.accept())!=null)
			{
				printInfo(sc);
			}
			else
			{
				System.out.println("Something is up when trying to connect!\n");
			}

			/* get the current date
            Date today = new Date(); */

			char[] today=new char[1024];

			in= stdIn.readLine();
			today=in.toCharArray();
			cbuf.put(today).flip();
			encoder.encode(cbuf, buf, true);
			buf.flip();
			System.out.println(buf.toString());

			MessageInfo messageInfo = MessageInfo.createOutgoing(null,0);
			sc.send(buf, messageInfo);


			cbuf.clear();
			buf.clear();

			sc.close();
		}
	}

	/* public static byte[] read(InputStream istream) 	//static for test
	{
	  ByteArrayOutputStream baos = new ByteArrayOutputStream();
	  byte[] buffer = new byte[1024]; // Experiment with this value
	  int bytesRead;
	try
	{

	  	while ((bytesRead = istream.read(buffer)) != -1)
	  	{
			baos.write(buffer, 0, bytesRead);
	  	}
	}
	catch(IOException e)
	{
		System.out.println("Error!");
	}
	  return baos.toByteArray();
	}*/
	public static void printInfo(SctpChannel sctpChannel)
	{
		try
		{
			System.out.println("sctpChannel.getRemoteAddresses() = " + sctpChannel.getRemoteAddresses());
			System.out.println("sctpChannel.getAllLocalAddresses() = " + sctpChannel.getAllLocalAddresses());
			System.out.println("sctpChannel.isConnectionPending() = " + sctpChannel.isConnectionPending());
			System.out.println("sctpChannel.isOpen() = " + sctpChannel.isOpen());
			System.out.println("sctpChannel.isRegistered() = " + sctpChannel.isRegistered());
			System.out.println("sctpChannel.provider() = " + sctpChannel.provider());
			System.out.println("sctpChannel.association() = " + sctpChannel.association());
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
}
